<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100">
            <el-form-item label="任务名称" prop="taskName">
              <el-input v-model="queryParams.taskName" placeholder="请输入任务名称" clearable />
            </el-form-item>
            <el-form-item label="任务类型" prop="taskType">
              <el-select v-model="queryParams.taskTypeId" placeholder="请选择任务类型" clearable>
                <el-option v-for="item in taskOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="用户类型">
              <el-select v-model="queryParams.userType" placeholder="请选择" clearable>
                <el-option v-for="dict in user_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="处理人" prop="handlerUserId">
              <user-input v-model="queryParams.handlerUserId" v-model:name="queryParams.handlerUserName" placeholder="请选择处理人"></user-input>
            </el-form-item>
            <el-form-item label="任务状态" prop="status">
              <el-select v-model="queryParams.status" clearable placeholder="请选择">
                <el-option v-for="dict in task_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="异议状态" prop="status">
              <el-select v-model="queryParams.objectionStatus" clearable placeholder="请选择">
                <el-option v-for="dict in task_objection_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="isVisible" label="预计开始时间" prop="expectedStartTime">
              <el-date-picker
                v-model="queryParams.expectedStartTime"
                clearable
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择预计开始时间"
              />
            </el-form-item>
            <el-form-item v-if="isVisible" label="预计结束时间" prop="expectedEndTime">
              <el-date-picker
                v-model="queryParams.expectedEndTime"
                clearable
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择预计结束时间"
              />
            </el-form-item>
            <el-form-item v-if="isVisible" label="实际开始时间" prop="actualStartTime">
              <el-date-picker
                v-model="queryParams.actualStartTime"
                clearable
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择实际开始时间"
              />
            </el-form-item>
            <el-form-item v-if="isVisible" label="实际结束时间" prop="actualEndTime">
              <el-date-picker v-model="queryParams.actualEndTime" clearable type="date" value-format="YYYY-MM-DD" placeholder="请选择实际结束时间" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              <el-button type="primary" @click="isVisible = !isVisible">{{ isVisible ? '收起' : '展开' }}</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['oa:task:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['oa:task:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()">修改 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['oa:task:objection']" type="success" plain :disabled="multiple" @click="handleObjection()">提交异议 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['oa:task:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              >删除
            </el-button>
          </el-col>
          <!--          <el-col :span="1.5">-->
          <!--            <el-button v-hasPermi="['oa:task:import']" type="warning" plain icon="Download" @click="downLoadImportTemplate"-->
          <!--              >下载任务导入模板-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button v-hasPermi="['oa:task:import']" type="warning" plain icon="Top" @click="handleImport">导入 </el-button>-->
          <!--          </el-col>-->
          <!-- <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oa:task:export']">导出</el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleDownLoadRestockingTemplate">下载补货计划模板 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="任务编码" align="center" prop="taskId" width="175" />
        <el-table-column label="任务名称" align="center" prop="taskName" width="150" show-overflow-tooltip />
        <el-table-column label="任务类型" align="center" prop="taskTypeName" width="100" />
        <el-table-column label="用户类型" align="center" prop="userType" width="100">
          <template #default="scope">{{ user_type.find((item) => item.value === scope.row.userType)?.label }}</template>
        </el-table-column>
        <el-table-column label="处理人" align="center" prop="handlerUserName" width="100" />
        <!-- 可操作状态 -->
        <el-table-column label="任务状态" align="center" prop="status" width="120">
          <template #default="scope">
            <el-dropdown trigger="click">
              <span class="el-dropdown-link">
                <el-button size="small" type="primary" :disabled="isNotTurn(Number(scope.row.status))" plain icon="ArrowDown">{{
                  task_status.find((item) => item.value == scope.row.status)?.label
                }}</el-button>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item icon="Operation" @click="changeTaskStatus(scope.row.taskId, '0')">[未开始] </el-dropdown-item>
                  <el-dropdown-item icon="Star" @click="changeTaskStatus(scope.row.taskId, '1')">[进行中] </el-dropdown-item>
                  <el-dropdown-item icon="Check" @click="changeTaskStatus(scope.row.taskId, '2')">[已完成] </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
        <el-table-column label="当前审批人" align="center" prop="reviewerName" width="120" />
        <el-table-column label="当前审批状态" align="center" prop="reviewerStatus" width="120">
          <template #default="scope">
            <el-button v-if="scope.row.reviewerStatus !== null && scope.row.reviewerStatus !== undefined" type="danger">
              {{ review_status.find((item) => item.value === scope.row.reviewerStatus)?.label }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="异议状态" align="center" prop="objectionStatus" width="100">
          <template #default="scope">
            <template v-if="scope.row.objectionStatus == 1">
              <el-button type="danger">异议</el-button>
            </template>
            <template v-else-if="scope.row.objectionStatus == 2">
              <el-button type="success">正常</el-button>
            </template>
            <template v-else>
              {{ task_objection_status.find((item) => item.value == scope.row.objectionStatus)?.label }}
            </template>
          </template>
        </el-table-column>
        <el-table-column label="预计开始时间" align="center" prop="expectedStartTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.expectedStartTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="预计结束时间" align="center" prop="expectedEndTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.expectedEndTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="实际开始时间" align="center" prop="actualStartTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.actualStartTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="实际结束时间" align="center" prop="actualEndTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.actualEndTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" p>
          <template #default="scope">
            <el-tooltip class="item" effect="dark" :content="scope.row.remark" placement="top-start">
              <p class="text-ellipsis whitespace-nowrap overflow-hidden">{{ scope.row.remark }}</p>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="子任务列表" align="center" :show-overflow-tooltip="true">
          <template #default="scope">
            <router-link :to="'/task/sub-task/index/' + scope.row.taskId" class="link-type">
              <span>子任务列表</span>
            </router-link>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
          <template #default="scope">
            <el-button v-if="['2', '3', '4'].includes(scope.row.status)" link type="primary" size="small" icon="View" @click="handleView(scope.row)"
              >查看
            </el-button>
            <el-tooltip content="提交异议" placement="top">
              <el-button v-hasPermi="['oa:task:objection']" link type="primary" @click="handleObjection(scope.row)"> 提交异议 </el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['oa:task:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['oa:task:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改任务对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="1200px" append-to-body>
      <el-form ref="taskFormRef" :model="form" :rules="rules" label-width="140px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务名称" prop="taskName">
              <el-input v-model="form.taskName" placeholder="请输入任务名称" :disabled="dialog.title === '修改任务'" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务类型" prop="taskTypeId">
              <el-select v-model="form.taskTypeId" :disabled="dialog.title === '修改任务'" placeholder="请选择任务类型" clearable>
                <el-option v-for="item in taskOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item v-if="showParentAsin" label="父产品ASIN" prop="parentAsin">
              <el-input v-model="form.parentAsin" type="textarea" placeholder="请输入父ASIN,多个用英文逗号分割,最多支持100个" :rows="2" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item v-if="showXieTiao(form.taskTypeId, form.userType)" label="协调人" prop="collaborators">
              <xie-tiao-task-user v-model="form.collaborators"></xie-tiao-task-user>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item v-if="showProductDevelopmentTaskUser(form.taskTypeId, form.userType)" label="上新协调人" prop="collaborators">
              <product-development-task-user v-model="form.collaborators"></product-development-task-user>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="处理人" prop="handlerUserName">
              <user-input v-model="form.handlerUserId" v-model:name="form.handlerUserName" :disabled="dialog.title === '修改任务'"></user-input>
            </el-form-item>
          </el-col>
          <el-col v-if="dialog.title === '修改任务'" :span="12">
            <el-form-item label="任务状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择">
                <el-option v-for="dict in task_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="任务总绩效分" prop="taskName">-->
          <!--              <el-input v-model="form.originalScore" placeholder="请输入任务总绩效分" :disabled="dialog.title === '修改任务'" />-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
        </el-row>
        <el-form-item label="任务内容" prop="content">
          <editor v-model="form.content" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="预计开始时间" prop="expectedStartTime">
              <el-date-picker
                v-model="form.expectedStartTime"
                clearable
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择预计开始时间"
                :disabled="dialog.title === '修改任务'"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计结束时间" prop="expectedEndTime">
              <el-date-picker
                v-model="form.expectedEndTime"
                clearable
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择预计结束时间"
                :disabled="dialog.title === '修改任务'"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="附件（多个）" prop="enclosure">
          <file-upload v-model="form.enclosure" />
          <el-button type="danger" round @click="downLoadErrorFile">下载错误文件</el-button>
        </el-form-item>
        <el-col :span="24">
          <el-form-item v-if="!form.processInstanceId" label="任务跟进人" prop="followCollaborators">
            <xie-tiao-task-user v-model="form.followCollaborators"></xie-tiao-task-user>
          </el-form-item>
        </el-col>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload">
          <i-ep-upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <!--            <div class="el-upload__tip"><el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据</div>-->
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="downLoadImportTemplate"
              >下载模板
            </el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Task" lang="ts">
import { pageTask, getTask, delTask, addTask, updateTask, turn, downLoadRestockingTemplate, objectionTask } from '@/api/task/task';
import { TaskVO, TaskQuery, TaskForm, Collaborator } from '@/api/task/task/types';
import { listTaskType } from '@/api/task/taskType';
import ProductDevelopmentTaskUser from '@/views/task/ProductDevelopmentTaskUser.vue';
import XieTiaoTaskUser from '@/views/task/XieTiaoTaskUser.vue';

import PersonSelect from '@/views/target/person/PersonSelect.vue';
import useUserStore from '@/store/modules/user';
import { globalHeaders } from '@/utils/request';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { task_status, user_type, review_status, task_objection_status } = toRefs<any>(
  proxy?.useDict('task_status', 'user_type', 'review_status', 'task_objection_status')
);
const taskList = ref<TaskVO[]>([]);
const taskOptions = ref([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);

const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const taskFormRef = ref<ElFormInstance>();
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const isVisible = ref(false);
const uploadRef = ref<ElUploadInstance>();

/*** 用户导入参数 */
const upload = reactive<ImportOption>({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/oa/task/importData'
});

const initFormData: any = {
  taskId: undefined,
  taskName: undefined,
  taskTypeId: undefined,
  content: undefined,
  fileName: undefined,
  expectedStartTime: undefined,
  expectedEndTime: undefined,
  actualStartTime: undefined,
  actualEndTime: undefined,
  // score: undefined,
  // originalScore: undefined,
  handlerUserId: undefined,
  userType: undefined,
  status: undefined,
  remark: undefined,
  collaborators: []
};
const validateEndTime = (rule, value, callback) => {
  if (form.value.expectedEndTime && form.value.expectedStartTime && form.value.expectedEndTime < form.value.expectedStartTime) {
    callback(new Error('预计结束时间不能小于预计开始时间'));
  } else {
    callback();
  }
};
const data = reactive<PageData<TaskForm, TaskQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    taskName: undefined,
    taskTypeId: undefined,
    content: undefined,
    expectedStartTime: undefined,
    expectedEndTime: undefined,
    actualStartTime: undefined,
    actualEndTime: undefined,
    // score: undefined,
    handlerUserId: undefined,
    userType: undefined,
    status: undefined,
    objectionStatus: undefined,
    params: {}
  },
  rules: {
    taskId: [{ required: false, message: '不能为空', trigger: 'blur' }],
    taskName: [{ required: true, message: '任务名称不能为空', trigger: 'blur' }],
    taskTypeId: [{ required: true, message: '任务类型不能为空', trigger: 'change' }],
    content: [{ required: true, message: '任务内容不能为空', trigger: 'blur' }],
    actualStartTime: [{ required: true, message: '实际开始时间不能为空', trigger: 'blur' }],
    actualEndTime: [{ required: true, message: '实际结束时间不能为空', trigger: 'blur' }],
    // score: [{ required: true, message: '绩效分不能为空', trigger: 'blur' }],
    handlerUserId: [{ required: true, message: '处理人不能为空', trigger: 'blur' }],
    userType: [{ required: true, message: '用户类型不能为空', trigger: 'change' }],
    status: [{ required: true, message: '任务状态不能为空', trigger: 'change' }],
    remark: [{ required: false, message: '备注不能为空', trigger: 'blur' }],
    expectedStartTime: [{ required: true, message: '预计开始时间不能为空', trigger: 'blur' }],
    expectedEndTime: [
      { required: true, message: '预计结束时间不能为空', trigger: 'blur' },
      { validator: validateEndTime, trigger: 'blur' }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

const showParentAsin = computed(() => Number(form.value.taskTypeId) == 10);

const showXieTiao = computed(() => (taskTypeId, userType) => {
  if (dialog.title === '修改任务') {
    return taskOptions.value.some((item) => {
      return item.name === '协调任务' && item.id === taskTypeId && Number(userType) === 0;
    });
  }
  return taskOptions.value.some((item) => {
    return item.name === '协调任务' && item.id === taskTypeId;
  });
});

const showProductDevelopmentTaskUser = computed(() => (taskTypeId, userType) => {
  if (dialog.title === '修改任务') {
    return taskOptions.value.some((item) => {
      return item.name === '上新任务' && item.id === taskTypeId && Number(userType) === 0;
    });
  }
  return taskOptions.value.some((item) => {
    return item.name === '上新任务' && item.id === taskTypeId;
  });
});

/** 查询任务列表 */
const getList = async () => {
  loading.value = true;
  const res = await pageTask(queryParams.value);
  taskList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 查询任务列表 */
const getTaskTypeList = async () => {
  loading.value = true;
  const res = await listTaskType();
  taskOptions.value = res.rows;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  taskFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: TaskVO[]) => {
  ids.value = selection.map((item) => item.taskId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加任务';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: TaskVO) => {
  reset();
  const _taskId = row?.taskId || ids.value[0];
  const res = await getTask(_taskId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改任务';
};

/** 查看按钮操作 */
const handleView = (row?: TaskVO) => {
  proxy.$tab.closePage(proxy.$route);
  proxy.$router.push({
    path: `/workflow/task/index`,
    query: {
      processInstanceId: row.processInstanceId,
      type: 'view'
    }
  });
};
const userStore = useUserStore();

const isNotTurn = (status: number) => {
  return status == 2 || status == 4;
};

const changeTaskStatus = async (taskId: string, state: string) => {
  loading.value = true;
  reset();
  const res = await turn({ taskId, status: state }).finally(() => (loading.value = false));
  if (res.code == 200) {
    proxy?.$modal.msgSuccess('操作成功');
    await getList();
  } else {
    proxy?.$modal.msgError(res.msg);
  }
  loading.value = false;
};

/** 提交按钮 */
const submitForm = () => {
  taskFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      // 普通协调任务
      if (form.value.collaborators && form.value.taskTypeId == '2') {
        for (const coordinator of form.value.collaborators) {
          if (!coordinator.expectedStartTime) {
            proxy?.$modal.msgError('协调人' + coordinator.handlerUserName + '预计开始时间不能为空');
            buttonLoading.value = false;
            return;
          }
          if (!coordinator.expectedEndTime) {
            proxy?.$modal.msgError('协调人' + coordinator.handlerUserName + '预计结束时间不能为空');
            buttonLoading.value = false;
            return;
          }
          const startTime = new Date(coordinator.expectedStartTime);
          const endTime = new Date(coordinator.expectedEndTime);

          if (endTime < startTime) {
            proxy?.$modal.msgError('协调人' + coordinator.handlerUserName + '预计结束时间不能小于预计开始时间');
            buttonLoading.value = false;
            return;
          }
        }
      } else if (form.value.collaborators && form.value.taskTypeId == '9') {
        // 上新任务
        for (const coordinator of form.value.collaborators) {
          if (!coordinator.expectedStartTime) {
            proxy?.$modal.msgError('协调人' + coordinator.handlerUserName + '预计开始时间不能为空');
            buttonLoading.value = false;
            return;
          }
          if (!coordinator.expectedEndTime) {
            proxy?.$modal.msgError('协调人' + coordinator.handlerUserName + '预计结束时间不能为空');
            buttonLoading.value = false;
            return;
          }
          if (!coordinator.handlerUserType) {
            proxy?.$modal.msgError('协调人' + coordinator.handlerUserName + '人员类型不能为空');
            buttonLoading.value = false;
            return;
          }
          if (!coordinator.productDevelopmentQuantity) {
            proxy?.$modal.msgError('协调人' + coordinator.handlerUserName + '上新数量不能为空');
            buttonLoading.value = false;
            return;
          }
          const startTime = new Date(coordinator.expectedStartTime);
          const endTime = new Date(coordinator.expectedEndTime);

          if (endTime < startTime) {
            proxy?.$modal.msgError('协调人' + coordinator.handlerUserName + '预计结束时间不能小于预计开始时间');
            buttonLoading.value = false;
            return;
          }
        }
      }

      if (form.value.followCollaborators) {
        for (const coordinator of form.value.followCollaborators) {
          if (!coordinator.expectedStartTime) {
            proxy?.$modal.msgError('任务跟进人' + coordinator.handlerUserName + '预计开始时间不能为空');
            buttonLoading.value = false;
            return;
          }
          if (!coordinator.expectedEndTime) {
            proxy?.$modal.msgError('任务跟进人' + coordinator.handlerUserName + '预计结束时间不能为空');
            buttonLoading.value = false;
            return;
          }
          const startTime = new Date(coordinator.expectedStartTime);
          const endTime = new Date(coordinator.expectedEndTime);

          if (endTime < startTime) {
            proxy?.$modal.msgError('任务跟进人' + coordinator.handlerUserName + '预计结束时间不能小于预计开始时间');
            buttonLoading.value = false;
            return;
          }
        }
      }
      // 退货率优化任务 父ASIN 必填
      if (Number(form.value.taskTypeId) == 10 && !form.value.parentAsin) {
        proxy?.$modal.msgError('退货率优化任务的父ASIN不能为空');
        buttonLoading.value = false;
        return;
      }

      if (form.value.taskId) {
        await updateTask(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addTask(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: TaskVO) => {
  const _taskIds = row?.taskId || ids.value;
  await proxy?.$modal.confirm('是否确认删除任务编号为"' + _taskIds + '"的数据项？').finally(() => (loading.value = false));
  await delTask(_taskIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 提交异议按钮操作 */
const handleObjection = async (row?: TaskVO) => {
  loading.value = true;
  const _taskIds = row?.taskId || ids.value;
  await proxy?.$modal.confirm('是否确认提交异议任务编号为"' + _taskIds + '"的数据项？').finally(() => (loading.value = false));
  await objectionTask(_taskIds).finally(() => (buttonLoading.value = false));
  proxy?.$modal.msgSuccess('修改成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'oa/task/export',
    {
      ...queryParams.value
    },
    `task_${new Date().getTime()}.xlsx`
  );
};

const handleDownLoadRestockingTemplate = async () => {
  proxy?.download(
    '/oa/task/downLoadRestockingTemplate',
    {
      ...queryParams.value
    },
    `补货计划模板_${new Date().getTime()}.xlsx`
  );
};

const downLoadErrorFile = async () => {
  proxy?.download(
    '/oa/task/downLoadErrorFile',
    {
      ...form.value
    },
    `错误信息模板_${new Date().getTime()}.xlsx`
  );
};

/** 下载模板操作 */
const downLoadImportTemplate = () => {
  proxy?.download('oa/task/downLoadImportTemplate', {}, `任务模板_${new Date().getTime()}.xlsx`);
};

/**文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: UploadFile) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.handleRemove(file);
  ElMessageBox.alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', {
    dangerouslyUseHTMLString: true
  });
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value?.submit();
}

/** 导入按钮操作 */
const handleImport = () => {
  upload.title = '版本号导入';
  upload.open = true;
};

onMounted(() => {
  getTaskTypeList();
  getList();
});
</script>

<style>
.editor {
  width: 100%;
}
</style>
